<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Article;
use App\Server\AliOSS;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;

class ArticleController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Article(), function (Grid $grid) {
            $grid->model()->orderByDesc('id');
            $grid->column('id')->sortable();
            $grid->column('title');
            $grid->column('img')->display(function($img) {
                return AliOSS::getThumbName($img);
            })->image(env('ALIYUN_DOMAIN'), 100);
            $grid->column('release_time');
            $grid->column('status', '状态')->switch();
            $grid->column('read_num', '阅读量');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();
        
            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');
        
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Article(), function (Show $show) {
            $show->field('id');
            $show->field('title');
            $show->field('img')->image();
            $show->field('release_time');
            $show->field('content')->unescape();
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Article(), function (Form $form) {
            $form->display('id');
            $form->text('title')->required();
            $form->datetime('release_time');
            $form->switch('status', '状态')->default(1);
            $form->image('img');
            $form->editor('content');
            $form->saving(function (Form $form) {
                if ($form->img) {
                    $oss = new AliOSS();
                    $oss->createThumb($form->img);
                }
            });
        });
    }
}
